using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using QW.Core.Exceptions;

namespace QW.Core.Encrypt
{
    /// <summary>
    /// MD5加密处理模块
    /// </summary>
    public sealed class MD5Helper
    {
        /// <summary>
        /// 获取Hash
        /// <para>默认UTF8</para>
        /// </summary>
        /// <param name="str"></param>
        /// <param name="ltype"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        public static string ComputeHash(string str, MD5EncryptLengthType ltype = MD5EncryptLengthType.Long, Encoding encode = null)
        {
            if (encode == null)
            {
                encode = Encoding.UTF8;
            }

            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] fromData;
            fromData = encode.GetBytes(str);
            byte[] targetData = md5.ComputeHash(fromData);
            StringBuilder builder = new StringBuilder(0x50);
            for (int i = 0; i < targetData.Length; i++)
            {
                builder.Append(targetData[i].ToString("x2"));
            }
            string result = builder.ToString();
            if (ltype == MD5EncryptLengthType.Short)
            {
                result = result.Substring(8, 16);
            }
            return result;
        }
        /// <summary>
        /// 获取Hash并Base64化
        /// <para>默认UTF8</para>
        /// </summary>
        /// <param name="str"></param>
        /// <param name="ltype"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        public static string ComputeHashToBase64(string str, MD5EncryptLengthType ltype = MD5EncryptLengthType.Long, Encoding encode = null)
        {
            string result = ComputeHash(str,ltype, encode);
            List<byte> lstBytes = new List<byte>();
            for (int i = 0; i < result.Length; i += 2)
            {
                lstBytes.Add(Convert.ToByte(result.Substring(i, 2), 16));
            }
            result = Convert.ToBase64String(lstBytes.ToArray());
            return result;
        }
    }
    /// <summary>
    /// Md5加密字符串长度
    /// </summary>
    public enum MD5EncryptLengthType
    {
        /// <summary>
        /// 16位
        /// </summary>
        Short = 16,
        /// <summary>
        /// 32位
        /// </summary>
        Long = 32
    }
}
